#!/usr/bin/env python3
"""
环境验证脚本
用于验证Python环境和依赖包是否正确安装

使用方法：
    python verify_environment.py
    python verify_environment.py --verbose
"""

import sys
import platform
import argparse
from typing import List, Tuple


def check_python_version() -> Tuple[bool, str]:
    """检查Python版本"""
    version = sys.version_info
    if version.major == 3 and version.minor >= 8:
        return True, f"✅ Python {version.major}.{version.minor}.{version.micro}"
    else:
        return False, f"❌ Python {version.major}.{version.minor}.{version.micro} (需要 Python 3.8+)"


def check_packages() -> List[Tuple[str, bool, str]]:
    """检查必需的包"""
    packages = [
        ('numpy', 'NumPy'),
        ('pandas', 'Pandas'),
        ('matplotlib', 'Matplotlib'),
        ('seaborn', 'Seaborn'),
        ('sklearn', 'Scikit-learn'),
        ('scipy', 'SciPy'),
    ]
    
    optional_packages = [
        ('tensorflow', 'TensorFlow'),
        ('torch', 'PyTorch'),
        ('jupyter', 'Jupyter'),
        ('pytest', 'Pytest'),
    ]
    
    results = []
    
    # 检查必需包
    for package, name in packages:
        try:
            module = __import__(package)
            version = getattr(module, '__version__', 'unknown')
            results.append((name, True, f"✅ {name} {version}"))
        except ImportError:
            results.append((name, False, f"❌ {name} 未安装"))
    
    # 检查可选包
    for package, name in optional_packages:
        try:
            module = __import__(package)
            version = getattr(module, '__version__', 'unknown')
            results.append((name, True, f"🔶 {name} {version} (可选)"))
        except ImportError:
            results.append((name, False, f"⚪ {name} 未安装 (可选)"))
    
    return results


def check_conda_environment() -> Tuple[bool, str]:
    """检查是否在conda环境中"""
    conda_env = sys.prefix
    if 'conda' in conda_env or 'miniconda' in conda_env or 'anaconda' in conda_env:
        env_name = conda_env.split('/')[-1] if '/' in conda_env else 'base'
        return True, f"✅ Conda环境: {env_name}"
    else:
        return False, "⚪ 不在Conda环境中"


def run_basic_tests(verbose: bool = False) -> bool:
    """运行基本功能测试"""
    tests_passed = 0
    total_tests = 0
    
    try:
        # NumPy测试
        import numpy as np
        total_tests += 1
        arr = np.array([1, 2, 3, 4, 5])
        assert arr.mean() == 3.0
        tests_passed += 1
        if verbose:
            print("  ✅ NumPy基本操作测试通过")
    except Exception as e:
        if verbose:
            print(f"  ❌ NumPy测试失败: {e}")
    
    try:
        # Pandas测试
        import pandas as pd
        total_tests += 1
        df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
        assert len(df) == 3
        tests_passed += 1
        if verbose:
            print("  ✅ Pandas基本操作测试通过")
    except Exception as e:
        if verbose:
            print(f"  ❌ Pandas测试失败: {e}")
    
    try:
        # Matplotlib测试
        import matplotlib
        matplotlib.use('Agg')  # 使用非交互式后端
        import matplotlib.pyplot as plt
        total_tests += 1
        fig, ax = plt.subplots()
        ax.plot([1, 2, 3], [1, 4, 2])
        plt.close(fig)
        tests_passed += 1
        if verbose:
            print("  ✅ Matplotlib基本操作测试通过")
    except Exception as e:
        if verbose:
            print(f"  ❌ Matplotlib测试失败: {e}")
    
    return tests_passed == total_tests


def main():
    parser = argparse.ArgumentParser(description='验证Python环境配置')
    parser.add_argument('--verbose', '-v', action='store_true', help='显示详细信息')
    args = parser.parse_args()
    
    print("🔍 Python环境验证")
    print("=" * 50)
    
    # 系统信息
    print(f"🖥️  系统: {platform.system()} {platform.release()}")
    print(f"🏗️  架构: {platform.machine()}")
    
    # Python版本检查
    python_ok, python_msg = check_python_version()
    print(python_msg)
    
    # Conda环境检查
    conda_ok, conda_msg = check_conda_environment()
    print(conda_msg)
    
    print("\n📦 包依赖检查")
    print("-" * 30)
    
    # 包检查
    package_results = check_packages()
    required_packages_ok = True
    
    for name, installed, message in package_results:
        print(message)
        if not installed and not message.startswith('🔶') and not message.startswith('⚪'):
            required_packages_ok = False
    
    print("\n🧪 功能测试")
    print("-" * 20)
    
    # 基本功能测试
    tests_ok = run_basic_tests(args.verbose)
    if tests_ok:
        print("✅ 所有基本功能测试通过")
    else:
        print("❌ 部分功能测试失败")
    
    print("\n📋 总结")
    print("=" * 20)
    
    if python_ok and required_packages_ok and tests_ok:
        print("🎉 环境配置完美！可以开始学习之旅了！")
        print("\n🚀 建议下一步：")
        print("   cd machine_learning_examples")
        print("   python test_all_examples.py --quick")
        return 0
    else:
        print("⚠️  环境配置存在问题，请检查以上错误信息")
        print("\n🔧 解决建议：")
        if not python_ok:
            print("   - 升级到Python 3.8或更高版本")
        if not conda_ok:
            print("   - 考虑使用conda环境管理：conda env create -f environment.yml")
        if not required_packages_ok:
            print("   - 安装缺失的包：pip install -r requirements.txt")
        if not tests_ok:
            print("   - 检查包版本兼容性")
        return 1


if __name__ == '__main__':
    sys.exit(main())